package com.example.websocket.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author ZhenWuWang
 */
@RestController()
public class WebSocketController
{
    private final SpringWebSocketHandler socketHandler;

    @Autowired
    public WebSocketController(SpringWebSocketHandler socketHandler)
    {
        this.socketHandler = socketHandler;
    }

    @RequestMapping(value = "/websocket/login", method = {RequestMethod.GET})
    public String login(HttpServletRequest request, HttpServletResponse response)
    {
        String userName = request.getParameter("userName");
        System.out.println(userName + "登录");
        HttpSession session = request.getSession(true);
        session.setAttribute("WEBSOCKET_USERNAME", userName);
//        return new ModelAndView("shareMsg");
        return "login success!";
    }

    @RequestMapping("/send")
    public String send(HttpServletRequest request)
    {
        String username = request.getParameter("userName");
        System.out.println("receiver:" + username);
        socketHandler.sendMessageToUser(username, new TextMessage("hello, this is a test!"));
        return "shareMsg";
    }
}
